// 文件名称：query.js
// 完整保存路径：miniprogram/pages/query/query.js
// 功能说明：数据查询页逻辑控制
// 使用说明：调用后端接口获取学生视力数据、干预记录等

const { getToken, getUserProfile } = require('../../utils/auth');
const { cacheData, getCachedData, getSyncStatus } = require('../../utils/sync');
const { mapMediaUrls } = require('../../utils/media');

Page({
  data: {
    activeTab: 0,           // 当前激活的标签页
    tabs: ['学生信息', '视力记录', '干预记录', '数据统计'],
    
    // 学生信息
    studentInfo: null,
    
    // 视力记录
    visionRecords: [],
    visionLoading: false,
    
    // 干预记录
    interventionRecords: [],
    interventionLoading: false,
    
    // 数据统计
    dataSummary: null,
    summaryLoading: false,
    
    // 通用状态
    loading: false,
    error: null,
    
    // 同步状态
    syncStatus: null,
    isOffline: false
  },

  /**
   * 页面加载时检查登录状态并加载数据
   */
  onLoad() {
    this.checkLoginAndLoadData();
    this.updateSyncStatus();
  },

  /**
   * 页面显示时刷新数据
   */
  onShow() {
    this.checkLoginAndLoadData();
    this.updateSyncStatus();
  },

  /**
   * 检查登录状态并加载数据
   */
  async checkLoginAndLoadData() {
    const token = getToken();
    if (!token) {
      wx.showToast({ 
        title: '请先登录', 
        icon: 'none' 
      });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/index/index' });
      }, 1500);
      return;
    }

    // 检查网络状态
    const app = getApp();
    this.setData({ isOffline: !app.globalData.isConnected });

    // 加载学生信息
    await this.loadStudentInfo();
    
    // 根据当前标签页加载对应数据
    this.loadTabData();
  },

  /**
   * 更新同步状态
   */
  updateSyncStatus() {
    const status = getSyncStatus();
    this.setData({ syncStatus: status });
  },

  /**
   * 加载学生信息
   */
  async loadStudentInfo() {
    try {
      this.setData({ loading: true, error: null });
      
      // 先尝试从缓存获取
      const cachedData = getCachedData('student_info');
      if (cachedData && !this.data.isOffline) {
        // 处理缓存数据的字段映射
        const processedCachedData = this.processStudentInfo(cachedData);
        this.setData({ 
          studentInfo: processedCachedData,
          loading: false 
        });
      }
      
      // 从服务器获取最新数据
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/query/student`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${getToken()}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data.success) {
        const data = response.data.data;
        
        // 处理字段映射和组合
        const processedData = this.processStudentInfo(data);
        
        this.setData({ 
          studentInfo: processedData,
          loading: false 
        });
        
        // 缓存数据（1小时过期）
        cacheData('student_info', processedData, 3600);
      } else {
        throw new Error(response.data.message || '获取学生信息失败');
      }
    } catch (error) {
      // 如果网络请求失败，尝试使用缓存数据
      const cachedData = getCachedData('student_info');
      if (cachedData) {
        // 处理缓存数据的字段映射
        const processedCachedData = this.processStudentInfo(cachedData);
        this.setData({ 
          studentInfo: processedCachedData,
          loading: false 
        });
        wx.showToast({ 
          title: '使用缓存数据', 
          icon: 'none' 
        });
      } else {
        this.setData({ 
          error: error.message || '获取学生信息失败',
          loading: false 
        });
        wx.showToast({ 
          title: error.message || '获取学生信息失败', 
          icon: 'none' 
        });
      }
    }
  },

  /**
   * 切换标签页
   */
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ activeTab: index });
    this.loadTabData();
  },

  /**
   * 根据当前标签页加载对应数据
   */
  loadTabData() {
    switch (this.data.activeTab) {
      case 0: // 学生信息
        // 学生信息已在loadStudentInfo中加载
        break;
      case 1: // 视力记录
        this.loadVisionRecords();
        break;
      case 2: // 干预记录
        this.loadInterventionRecords();
        break;
      case 3: // 数据统计
        this.loadDataSummary();
        break;
    }
  },

  /**
   * 加载视力记录
   */
  async loadVisionRecords() {
    try {
      this.setData({ visionLoading: true });
      
      // 先尝试从缓存获取
      const cachedData = getCachedData('vision_records');
      if (cachedData && !this.data.isOffline) {
        this.setData({ 
          visionRecords: cachedData,
          visionLoading: false 
        });
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/query/vision`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${getToken()}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data.success) {
        // 后端返回的是分页结构，需要提取records数组
        const data = response.data.data?.records || [];
        // 预处理视力记录数据，格式化需要显示的字段
        const processedData = data.map(record => ({
          ...record,
          formatted_measure_date: this.formatDate(record.measure_date),
          formatted_vision_level: this.formatVisionLevel(record.vision_level)
        }));
        this.setData({ 
          visionRecords: processedData,
          visionLoading: false 
        });
        
        // 缓存数据（30分钟过期）
        cacheData('vision_records', processedData, 1800);
      } else {
        throw new Error(response.data.message || '获取视力记录失败');
      }
    } catch (error) {
      // 如果网络请求失败，尝试使用缓存数据
      const cachedData = getCachedData('vision_records');
      if (cachedData) {
        this.setData({ 
          visionRecords: cachedData,
          visionLoading: false 
        });
        wx.showToast({ 
          title: '使用缓存数据', 
          icon: 'none' 
        });
      } else {
        this.setData({ visionLoading: false });
        wx.showToast({ 
          title: error.message || '获取视力记录失败', 
          icon: 'none' 
        });
      }
    }
  },

  /**
   * 加载干预记录
   */
  async loadInterventionRecords() {
    try {
      this.setData({ interventionLoading: true });
      
      // 先尝试从缓存获取
      const cachedData = getCachedData('intervention_records');
      if (cachedData && !this.data.isOffline) {
        // 兼容旧缓存中没有预计算 label 的情况
        const patched = cachedData.map(r => ({
          ...r,
          intervention_type_label: this._mapInterventionType(r.intervention_type)
        }));
        this.setData({ 
          interventionRecords: patched,
          interventionLoading: false 
        });
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/query/intervention`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${getToken()}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data.success) {
        // 后端返回的是分页结构，需要提取records数组
        const data = response.data.data?.records || [];
        // 预处理 image_urls -> 全量 URL（保持最小规则，不做“纠错”），并预计算显示字段
        const enriched = data.map(r => ({
          ...r,
          image_urls: mapMediaUrls(r.image_urls),
          intervention_type_label: this._mapInterventionType(r.intervention_type),
          formatted_intervention_date: this.formatDate(r.intervention_date),
          formatted_operation_time: this.formatDate(r.operation_time)
        }));
        this.setData({ 
          interventionRecords: enriched,
          interventionLoading: false 
        });
        
        // 缓存数据（30分钟过期）
        cacheData('intervention_records', enriched, 1800);
      } else {
        throw new Error(response.data.message || '获取干预记录失败');
      }
    } catch (error) {
      // 如果网络请求失败，尝试使用缓存数据
      const cachedData = getCachedData('intervention_records');
      if (cachedData) {
        this.setData({ 
          interventionRecords: cachedData,
          interventionLoading: false 
        });
        wx.showToast({ 
          title: '使用缓存数据', 
          icon: 'none' 
        });
      } else {
        this.setData({ interventionLoading: false });
        wx.showToast({ 
          title: error.message || '获取干预记录失败', 
          icon: 'none' 
        });
      }
    }
  },

  /**
   * 加载数据统计
   */
  async loadDataSummary() {
    try {
      this.setData({ summaryLoading: true });
      
      // 先尝试从缓存获取
      const cachedData = getCachedData('data_summary');
      if (cachedData && !this.data.isOffline) {
        this.setData({ 
          dataSummary: cachedData,
          summaryLoading: false 
        });
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/query/summary`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${getToken()}`
          },
          success: resolve,
          fail: reject
        });
      });

      if (response.data.success) {
        const data = response.data.data;
        this.setData({ 
          dataSummary: data,
          summaryLoading: false 
        });
        
        // 缓存数据（1小时过期）
        cacheData('data_summary', data, 3600);
      } else {
        throw new Error(response.data.message || '获取数据统计失败');
      }
    } catch (error) {
      // 如果网络请求失败，尝试使用缓存数据
      const cachedData = getCachedData('data_summary');
      if (cachedData) {
        this.setData({ 
          dataSummary: cachedData,
          summaryLoading: false 
        });
        wx.showToast({ 
          title: '使用缓存数据', 
          icon: 'none' 
        });
      } else {
        this.setData({ summaryLoading: false });
        wx.showToast({ 
          title: error.message || '获取数据统计失败', 
          icon: 'none' 
        });
      }
    }
  },

  /**
   * 刷新数据
   */
  onPullDownRefresh() {
    this.loadTabData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 查看视力记录详情
   */
  viewVisionDetail(e) {
    const record = e.currentTarget.dataset.record;
    wx.navigateTo({
      url: `/pages/vision-detail/vision-detail?record=${JSON.stringify(record)}`
    });
  },

  /**
   * 查看干预记录详情
   */
  viewInterventionDetail(e) {
    const record = e.currentTarget.dataset.record;
    wx.navigateTo({
      url: `/pages/intervention-detail/intervention-detail?record=${JSON.stringify(record)}`
    });
  },

  /**
   * 处理学生信息字段映射
   */
  processStudentInfo(data) {
    console.log('processStudentInfo 输入数据:', data);
    console.log('性别字段:', data.gender);
    console.log('生日字段:', data.birthday);
    
    // 组合年级班级信息
    let gradeClassCombined = '';
    if (data.extension && data.extension.grade) {
      gradeClassCombined = data.extension.grade;
      if (data.class_name) {
        gradeClassCombined += ` ${data.class_name}`;
      }
    } else if (data.class_name) {
      gradeClassCombined = data.class_name;
    }
    
    // 格式化生日
    let formattedBirthday = '';
    if (data.birthday) {
      formattedBirthday = this.formatDate(data.birthday);
    }
    
    const result = {
      ...data,
      grade_class_combined: gradeClassCombined || '未填写',
      formatted_birthday: formattedBirthday
    };
    
    console.log('processStudentInfo 处理结果:', result);
    console.log('结果中的性别:', result.gender);
    console.log('结果中的生日:', result.birthday);
    console.log('格式化后的生日:', result.formatted_birthday);
    
    return result;
  },

  /**
   * 格式化日期
   */
  formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  /**
   * 格式化视力等级
   */
  formatVisionLevel(level) {
    // 后端已返回中文的视力等级，直接使用
    if (!level) return '未知';
    return level;
  },

  /**
   * 格式化干预方式
   */
  formatInterventionType(type) {
    const typeMap = {
      'medication': '药物治疗',
      'optical_correction': '光学矫正',
      'behavioral_intervention': '行为干预',
      'environmental_modification': '环境改善',
      'nutritional_supplement': '营养补充',
      'physical_exercise': '体育锻炼',
      'other': '其他',
      '耳穴压丸': '耳穴压丸',
      '刮痧': '刮痧',
      '艾灸': '艾灸',
      '中药熏蒸': '中药熏蒸',
      '热灸训练': '热灸训练',
      '热磁脉冲': '热磁脉冲',
      '拔罐': '拔罐'
    };
    return typeMap[type] || type;
  }
  ,
  /**
   * 内部映射方法（与 formatInterventionType 同逻辑，供数据预处理使用）
   */
  _mapInterventionType(type) {
    return this.formatInterventionType(type || '');
  }
});